<script setup>
  import { ref, onMounted } from 'vue'
  import { getListApi } from '@/apis/task'

  // 1. 获取任务列表
  const taskList = ref([])
  const nextPage = ref(1)
  const pageSize = ref(10)
  const isEmpty = ref(false)
  // 是否有更多数据
  const hasMore = ref(false)

  const getTaskList = async (page = 1, pageSize = 10) => {
    const { code, data } = await getListApi(1, page, pageSize)
    if (code !== 200) return uni.utils.toast()
    // 页面为 1 时，清空数组
    if (page === 1) taskList.value = []
    // taskList.value = data.items || []
    taskList.value = [...taskList.value, ...(data.items || [])]
    // 计算下一页页码
    nextPage.value = ++data.page
    isEmpty.value = data.items.length === 0
    // 判断还有没有更多的数据
    hasMore.value = nextPage.value <= data.pages
  }

  onMounted(() => {
    getTaskList()
  })

  // 2. 监听页面是否滚动到底部
  const onScrollToLower = () => {
    // 没有更多数据时则不需要再请求了
    if (!hasMore.value) return uni.utils.toast('没有更多数据了~')
    // 获取下一页数据
    getTaskList(nextPage.value)
  }

  // 3. 监听用户的下拉操作
  const isTriggered = ref(false)
  const onScrollViewRefresh = async () => {
    isTriggered.value = true
    await getTaskList()
    isTriggered.value = false
  }
</script>

<template>
  <scroll-view
    scroll-y
    refresher-enabled
    :refresher-triggered="isTriggered"
    class="scroll-view"
    @scrolltolower="onScrollToLower"
    @refresherrefresh="onScrollViewRefresh"
  >
    <view class="scroll-view-wrapper">
      <view class="task-card" v-for="item in taskList" :key="item.id">
        <navigator
          hover-class="none"
          :url="`/subpkg_task/detail/index?id=${item.id}`"
        >
          <view class="header">
            <text class="no">任务编号: {{ item.transportTaskId }}</text>
            <!-- <text class="status">已延迟</text> -->
          </view>
          <view class="body">
            <view class="timeline">
              <view class="line">{{ item.startAddress }}</view>
              <view class="line">{{ item.endAddress }}</view>
            </view>
          </view>
        </navigator>
        <view class="footer">
          <view class="label">提货时间</view>
          <view class="time">{{ item.planDepartureTime }}</view>
          <!-- 是否可以提货 -->
          <navigator
            v-if="item.enablePickUp"
            hover-class="none"
            :url="`/subpkg_task/pickup/index?id=${item.id}`"
            class="action"
            >提货</navigator
          >
          <button v-else disabled class="action">提货</button>
        </view>
      </view>
      <view v-if="isEmpty" class="task-blank">无待提货物</view>
    </view>
  </scroll-view>
</template>

<style lang="scss" scoped>
  @import './styles.scss';
</style>
